package com.pan.tools;


import com.pan.entity.Result;
import com.pan.enume.ResultEnum;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Component
public class RedisTools {

//    这个不行 会有乱码，要用下面的
//    @Resource
//    private RedisTemplate redisTemplate;


    @Resource
    public StringRedisTemplate stringRedisTemplate;

    public Result set(String key, String value){

        stringRedisTemplate.opsForValue().set(key,value);
        return new Result(ResultEnum.SUCCESS);
    }

    public Result<String> get(String key){
        String value = (String) stringRedisTemplate.opsForValue().get(key);
        Result<String> result = new Result(ResultEnum.SUCCESS);
        result.setData(value);
        return result;
    }

    public Result hset(String key, Map fv){
        stringRedisTemplate.opsForHash().putAll(key,fv);
        Result result = new Result(ResultEnum.SUCCESS);
        return result;
    }

    public Result<Object> hget(String key, String hashKey){
        Object data = stringRedisTemplate.opsForHash().get(key,hashKey);
        return new Result(ResultEnum.SUCCESS,data);
    }

    public Result<Map<Object,Object>> hgetall(String key){
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(key);
        return new Result(ResultEnum.SUCCESS,map);
    }

    public Result sadd(String key, String... values) {
        stringRedisTemplate.opsForSet().add(key, values);
        return new Result(ResultEnum.SUCCESS);
    }

    public Result<Set> smembers(String key) {
        Set set = stringRedisTemplate.opsForSet().members(key);
        Result<Set> result = new Result<>(ResultEnum.SUCCESS);
        result.setData(set);
        return result;
    }

    /**
     *
     * @param key
     * @param timeout 过期时间 日
     * @return
     */
    public Result expire(String key,Long timeout){
        stringRedisTemplate.expire(key,timeout, TimeUnit.DAYS);
        return new Result(ResultEnum.SUCCESS);
    }

    public Result del(String key){
        stringRedisTemplate.delete(key);
        return new Result(ResultEnum.SUCCESS);
    }

    public Result<Boolean> exists(String key){
        Boolean is = stringRedisTemplate.hasKey(key);
        return new Result<>(ResultEnum.SUCCESS,is);
    }

}
